<template>
  <div class="div_storemsg_body">
    <beautiful-chat :onMessageWasSent="onMessageWasSent" :messageList="messageList" :close="()=>$router.go(-1)"
      :showEmoji="true" :showFile="true" :colors="colors" :showCloseButton="true" :video="true"
      :always-scroll-to-bottom="alwaysScrollToBottom" :disableUserListToggle="false" :messageStyling="messageStyling"
      :open="()=>{}" :scrollToTop="handleScrollToTop" @onType="handleOnInputMsg" :upload="onUpload">
      <!-- 标题 -->
      <template #header>
        <div style="margin-left:50px;margin-top:20px">{{title}}</div>
      </template>
      <!-- 消息内容 -->
      <template v-slot:text-message-body="{ message }">

      </template>

    </beautiful-chat>
  </div>
</template>
<script>
  import {
    Toast,
  } from 'vant'

  export default {
    name: 'chatmsg',
    data() {
      return {
        messageList: [],
        colors: {
          header: {
            bg: '#4e8cff',
            text: '#ffffff'
          },
          launcher: {
            bg: '#4e8cff'
          },
          messageList: {
            bg: '#ffffff'
          },
          sentMessage: {
            bg: '#4e8cff',
            text: '#ffffff'
          },
          receivedMessage: {
            bg: '#eaeaea',
            text: '#222222'
          },
          userInput: {
            bg: '#f4f7f9',
            text: '#565867'
          }
        },
        //是否允许自动滚动到底部
        alwaysScrollToBottom: true,
        messageStyling: true,
        title: '', //标题
        msg: {
          recevie: {
            //消息接收人的id
            userId: 0,
            //消息接收人的用户名
            userName: '',
            //消息接收人的名称
            name: '',
            //消息接收人的头像
            heardImgUrl: '',
          },
          send: {
            //发送人用户id
            userId: '',
            //发送人账号
            userName: '',
            //发送人名称
            name: '',
            //发送人的头像
            heardImgUrl: '',
          }
        },
        pag: {
          pageIndex: 1, //当前页数
          pageSize: 10, //显示的条数
        },
        dataComplateStatus: false, //消息的完成状态
      }
    },
    methods: {
      //消息发送
      async onMessageWasSent(message) {
        //消息内容
        var messageContent = "";
        //消息类型
        var messageType = 0;

        if (message.type == "text") {
          messageContent = message.data.text;
        } else if (message.type == "emoji") {
          messageContent = message.data.emoji;
          messageType = 1;
        } else if (message.type == "file") {
          messageContent = message.data.file.url;
          messageType = 2;
        }
        message.headUrl = this.msg.send.heardImgUrl;
        //发送消息
        await this.$taskSocket.sendMessage('sendMessage', {
          SendUserId: this.msg.send.userId,
          SendUser: this.msg.send.userName,
          SendHeardImgUrl: this.msg.send.heardImgUrl,
          RecevieUserId: this.msg.recevie.userId,
          RecevieUser: this.msg.recevie.userName,
          RecevieHeardImgUrl: this.msg.recevie.heardImgUrl,
          ChatContent: messageContent,
          ContentType: messageType
        });

        //合并数组
        this.messageList = [...this.messageList, message]
      },
      //接收消息
      receivedMessage(msg) {
        //验证消息类型
        var type = 'text';
        //内容数据
        var data = {};
        if (msg.ContentType == 0) {
          type = 'text';
          data = {
            text: msg.ChatContent
          }
        } else if (msg.ContentType == 1) {
          type = 'emoji';
          data = {
            emoji: msg.ChatContent
          }
        } else if (msg.ContentType == 2) {
          type = 'file';
          data = {
            file: {
              url: msg.ChatContent
            }
          }
        }
        //构建消息信息
        var message = {
          type: type,
          author: msg.SendUser,
          headUrl: msg.SendHeardImgUrl ? msg.SendHeardImgUrl : './static/imgs/defaultavatar.png',
          data: data
        };
        //合并数组
        this.messageList = [...this.messageList, message]
      },
      //加载数据
      async loadData() {
        Toast.loading({
          message: '加载中...',
          forbidClick: false,
          loadingType: 'spinner',
          duration: 0
        });
        var res = await this.$ajax.get(
          `/api/chatmessage?userId=${this.msg.send.userId}&receiveUserId=${this.msg.recevie.userId}&pageIndex=${this.pag.pageIndex}&pageSize=${this.pag.pageSize}`
        );
        //清除提示框
        Toast.clear();
        //验证数据的返回值
        if (res.status == 1) {
          Toast.fail(res.msg);
          return;
        }
        //验证数据是否加载完成
        if (res.data == null || res.data.length < this.pag.pageSize) {
          this.dataComplateStatus = true;
        }
        //格式化数据
        var messageData = [...res.data].map(item => {
          //验证消息类型
          var type = 'text';
          //内容数据
          var data = {};
          if (item.contentType == 0) {
            type = 'text';
            data = {
              text: item.chatContent,
            }
          } else if (item.contentType == 1) {
            type = 'emoji';
            data = {
              emoji: item.chatContent
            }
          } else if (item.contentType == 2) {
            type = 'file';
            data = {
              file: {
                url: item.chatContent
              }
            }
          }
          var obj = {
            id: item.id,
            type: type,
            author: item.sendUserId == this.msg.send.userId ? 'me' : item.recevieUserId,
            headUrl: item.sendUserId === this.msg.send.userId || item.recevieUserId === this.msg.send.userId ?
              item.sendHeardImgUrl : item.recevieHeardImgUrl,
            data: data
          }
          if (!obj.headUrl) {
            obj.headUrl = './static/imgs/defaultavatar.png'
          }
          return obj
        });
        this.messageList = messageData.concat(...this.messageList)
      },
      //更新消息的状态
      async updateMessageRead(id) {
        await this.$taskSocket.sendMessage('updateMessageRead', {
          id: id
        });
      },
      //滚动到顶部的时候触发
      async handleScrollToTop() {
        //验证数据是否已经加载完成
        if (!this.dataComplateStatus) {
          //页数加一
          this.pag.pageIndex = this.pag.pageIndex + 1;
          //加载数据
          await this.loadData();
        }
        //验证数据是否已经加载完成
        if (this.dataComplateStatus) {
          return true;
        }
        return false;
      },
      //用户输入消息时候触发
      handleOnInputMsg() {

      },
      //文件上传的处理
      //需要返回一个filejson对象
      async onUpload(file) {
        Toast.loading({
          message: '正在上传...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        });
        var timestamp = new Date().getTime()
        var res = await this.$ajax.uploadFile(this.$config.fileServer + `chatmsg/${timestamp}${file.name}`, file);
        //清除提示框
        Toast.clear();
        return {
          url: `${this.$config.fileServer}${res.requestPath}`
        };
      },
      //获取当前聊天用户的基本信息
      async getUserBase() {
        var res = await this.$ajax.get(`/api/user/base/${this.msg.recevie.userId}`);
        if (res.status == 1) {
          Toast.fail(res.msg);
          return;
        }
        this.msg.recevie.userName = res.data.userName;
        this.msg.recevie.name = res.data.name;
        this.msg.recevie.heardImgUrl = res.data.heardImgUrl;
      }
    },
    async mounted() {
      //获取用户信息
      var userInfo = this.$user.getUserInfo();
      this.msg.send.userId = userInfo.id;
      this.msg.send.userName = userInfo.userName;
      this.msg.send.name = userInfo.name;
      this.msg.send.heardImgUrl = userInfo.heardImgUrl;
      //获取接收人用户id
      this.msg.recevie.userId = this.$route.params.id;
      //获取消息接收人的信息
      await this.getUserBase();
      //显示标题
      this.title = this.msg.recevie.name;
      //显示底部栏
      this.$store.commit('updateShowFoot', false)
      this.$eventBus.publish('connectionSocket');
      //接收消息
      this.$eventBus.subscribe('reviceMessage', async msg => {
        if (msg.SendUserId != this.msg.recevie.userId) {
          return;
        }
        //处理接收的消息
        this.receivedMessage(msg);
        //更新消息已读
        await this.updateMessageRead(msg.Id);
      });
      //获取历史消息
      await this.loadData();
    }
  }

</script>
